<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Controller\user;

use App\Service\ConfigService;
use App\Service\ServantConfigService;
use App\Service\UploadService;
use App\Middleware\User\UserMiddleware;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpMessage\Upload\UploadedFile;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;
use Psr\SimpleCache\InvalidArgumentException;

/**
 * 上传控制器
 *
 * @AutoController()
 * @author 刘兴永(aile8880@qq.com)
 * @package App\Controller\admin
 */
class UploadController extends Controller
{
    /**
     * 上传服务
     *
     * @Inject
     * @var UploadService
     */
    private $service;

    /**
     * 配置文件
     * @Inject
     * @var ConfigService
     */
    private $config_service;

    /**
     * @Inject
     * @var ServantConfigService
     */
    private $servant_config_service;


    /**
     * 文件上传，自动判断多文件和单文件上传
     */
    public function file()
    {
        $files = $this->request->file('file');

        $result = [];

        if (is_object($files) && $files instanceof UploadedFile) {
            // 单个文件上传
            $result[] = $this->service->handle($files);
        }
        else if (is_array($files) && count($files) > 0){
            // 多个文件上传
            foreach ($files as $file) {
                if (!$file instanceof UploadedFile) continue;
                $result[] = $this->service->handle($file);
            }
        }
        else {
            $this->error('UPLOAD.PLEASE_SELECT_FILE');
        }

        $this->success([
            'domain' => gConfig('ali_oss_domain'),
            'result' => $result
        ]);
    }

    /**
     * 刷新配置文件
     */
    public function refresh()
    {
        $this->config_service->delete();
        $this->success();
    }

    /**
     * 刷新分佣配置文件
     */
    public function servantRefresh()
    {
        $this->servant_config_service->delete();

        $this->success();
    }

}